# -*- coding: utf-8 -*-
"""
系统管理API路由

按照模块文档-09-系统管理.md规范实现完整的系统管理功能：
- 2.2 系统配置管理
- 2.3 数据维护管理  
- 2.4 系统监控管理
- 2.5 系统集成管理
"""

from typing import Dict, List, Optional, Any
from fastapi import APIRouter, Depends, HTTPException, Request, UploadFile, File
from sqlalchemy.orm import Session
from pydantic import BaseModel, Field

from ...core.database import get_db
from ...core.security import get_current_user
from ...models.rbac import User
from ...models.system_config import ConfigCategory, ConfigType
from ...services.system_config_service import SystemConfigService
from ...core.exceptions import ValidationError, NotFoundError, BusinessLogicError

# 导入子模块路由
from .system.data_maintenance import router as data_maintenance_router
from .system.monitoring import router as monitoring_router
from .system.integration import router as integration_router

router = APIRouter()

# 注册子模块路由
router.include_router(
    data_maintenance_router, 
    prefix="/data-maintenance", 
    tags=["数据维护管理"]
)
router.include_router(
    monitoring_router, 
    prefix="/monitoring", 
    tags=["系统监控管理"]
)
router.include_router(
    integration_router, 
    prefix="/integration", 
    tags=["系统集成管理"]
)


# === Pydantic 模型定义 ===

class ConfigUpdateRequest(BaseModel):
    """配置更新请求模型"""
    config_value: Any = Field(..., description="配置值")
    change_reason: Optional[str] = Field(None, description="变更原因")

class BatchConfigUpdateRequest(BaseModel):
    """批量配置更新请求模型"""
    configs: Dict[str, Any] = Field(..., description="配置字典")
    change_reason: Optional[str] = Field(None, description="变更原因")

class ConfigExportRequest(BaseModel):
    """配置导出请求模型"""
    category: Optional[ConfigCategory] = Field(None, description="配置分类")
    include_sensitive: bool = Field(False, description="是否包含敏感配置")

class ConfigImportRequest(BaseModel):
    """配置导入请求模型"""
    import_data: Dict[str, Any] = Field(..., description="导入数据")
    overwrite: bool = Field(False, description="是否覆盖现有配置")

class ConnectionTestRequest(BaseModel):
    """连接测试请求模型"""
    config_type: str = Field(..., description="配置类型")
    config_data: Dict[str, Any] = Field(..., description="配置数据")


# === API 路由实现 ===

@router.get("/", summary="系统信息", description="获取系统基本信息")
async def get_system_info():
    """获取系统基本信息"""
    return {
        "name": "CRM旅游管理系统",
        "version": "2.0.0",
        "api_version": "v1",
        "status": "running",
        "message": "系统管理API服务正常运行"
    }


@router.get("/configs", summary="获取配置列表", description="获取系统配置列表，支持分类筛选")
async def get_configs(
    category: Optional[ConfigCategory] = None,
    group_name: Optional[str] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    获取系统配置列表
    
    - **category**: 配置分类筛选
    - **group_name**: 分组名称筛选
    """
    try:
        service = SystemConfigService(db)
        
        if group_name:
            # 获取指定分组的配置
            configs = service.get_configs_by_group(group_name, category)
            return {
                "success": True,
                "data": configs,
                "message": f"获取分组 {group_name} 配置成功"
            }
        elif category:
            # 获取指定分类的配置
            configs = service.get_configs_by_category(category)
            return {
                "success": True,
                "data": configs,
                "message": f"获取分类 {category.value} 配置成功"
            }
        else:
            # 获取所有分组信息
            groups = service.get_all_groups()
            return {
                "success": True,
                "data": groups,
                "message": "获取配置分组信息成功"
            }
            
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取配置失败: {str(e)}")


@router.get("/configs/{config_key}", summary="获取单个配置", description="获取指定键的配置值")
async def get_config(
    config_key: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取单个配置项的值"""
    try:
        service = SystemConfigService(db)
        value = service.get_config(config_key)
        
        if value is None:
            raise HTTPException(status_code=404, detail=f"配置项 {config_key} 不存在")
            
        return {
            "success": True,
            "data": {
                "config_key": config_key,
                "config_value": value
            },
            "message": "获取配置成功"
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取配置失败: {str(e)}")


@router.put("/configs/{config_key}", summary="更新配置", description="更新指定键的配置值")
async def update_config(
    config_key: str,
    request_data: ConfigUpdateRequest,
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """更新配置项的值"""
    try:
        service = SystemConfigService(db)
        
        # 获取客户端信息
        client_ip = request.client.host
        user_agent = request.headers.get("user-agent", "")
        
        success = service.set_config(
            key=config_key,
            value=request_data.config_value,
            operator=current_user.username,
            reason=request_data.change_reason,
            client_ip=client_ip,
            user_agent=user_agent
        )
        
        if success:
            return {
                "success": True,
                "message": f"配置 {config_key} 更新成功"
            }
        else:
            raise HTTPException(status_code=400, detail="配置更新失败")
            
    except ValidationError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except NotFoundError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except BusinessLogicError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新配置失败: {str(e)}")


@router.post("/configs/batch", summary="批量更新配置", description="批量更新多个配置项")
async def batch_update_configs(
    request_data: BatchConfigUpdateRequest,
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """批量更新配置项"""
    try:
        service = SystemConfigService(db)
        
        # 获取客户端信息
        client_ip = request.client.host
        user_agent = request.headers.get("user-agent", "")
        
        results = service.batch_set_configs(
            configs=request_data.configs,
            operator=current_user.username,
            reason=request_data.change_reason,
            client_ip=client_ip,
            user_agent=user_agent
        )
        
        success_count = sum(1 for success in results.values() if success)
        total_count = len(results)
        
        return {
            "success": True,
            "data": {
                "results": results,
                "success_count": success_count,
                "total_count": total_count
            },
            "message": f"批量更新完成，成功 {success_count}/{total_count} 项"
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"批量更新配置失败: {str(e)}")


@router.get("/configs/{config_key}/history", summary="配置变更历史", description="获取配置项的变更历史记录")
async def get_config_history(
    config_key: str,
    limit: int = 50,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取配置变更历史"""
    try:
        service = SystemConfigService(db)
        history = service.get_config_history(config_key, limit)
        
        return {
            "success": True,
            "data": history,
            "message": f"获取配置 {config_key} 变更历史成功"
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取配置历史失败: {str(e)}")


@router.post("/configs/export", summary="导出配置", description="导出系统配置到JSON文件")
async def export_configs(
    request_data: ConfigExportRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """导出系统配置"""
    try:
        service = SystemConfigService(db)
        export_data = service.export_configs(
            category=request_data.category,
            include_sensitive=request_data.include_sensitive
        )
        
        return {
            "success": True,
            "data": export_data,
            "message": "配置导出成功"
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"导出配置失败: {str(e)}")


@router.post("/configs/import", summary="导入配置", description="从JSON数据导入系统配置")
async def import_configs(
    request_data: ConfigImportRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """导入系统配置"""
    try:
        service = SystemConfigService(db)
        result = service.import_configs(
            import_data=request_data.import_data,
            operator=current_user.username,
            overwrite=request_data.overwrite
        )
        
        return {
            "success": True,
            "data": result,
            "message": f"配置导入完成，成功 {result['success_count']} 项"
        }
        
    except ValidationError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except BusinessLogicError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"导入配置失败: {str(e)}")


@router.post("/configs/import/file", summary="文件导入配置", description="从上传的JSON文件导入配置")
async def import_configs_from_file(
    file: UploadFile = File(...),
    overwrite: bool = False,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """从文件导入配置"""
    try:
        # 验证文件类型
        if not file.filename.endswith('.json'):
            raise HTTPException(status_code=400, detail="只支持JSON文件格式")
        
        # 读取文件内容
        content = await file.read()
        import json
        import_data = json.loads(content.decode('utf-8'))
        
        service = SystemConfigService(db)
        result = service.import_configs(
            import_data=import_data,
            operator=current_user.username,
            overwrite=overwrite
        )
        
        return {
            "success": True,
            "data": result,
            "message": f"配置文件导入完成，成功 {result['success_count']} 项"
        }
        
    except json.JSONDecodeError:
        raise HTTPException(status_code=400, detail="JSON文件格式错误")
    except ValidationError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except BusinessLogicError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"导入配置文件失败: {str(e)}")


@router.post("/configs/test-connection", summary="测试连接", description="测试配置的连接性（如数据库、邮件服务器等）")
async def test_config_connection(
    request_data: ConnectionTestRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """测试配置连接"""
    try:
        service = SystemConfigService(db)
        result = service.test_config_connection(
            config_type=request_data.config_type,
            config_data=request_data.config_data
        )
        
        return {
            "success": result["success"],
            "data": result,
            "message": result["message"]
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"测试连接失败: {str(e)}")


@router.post("/configs/initialize", summary="初始化默认配置", description="初始化系统默认配置项")
async def initialize_default_configs(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """初始化默认配置"""
    try:
        service = SystemConfigService(db)
        success = service.initialize_default_configs(operator=current_user.username)
        
        if success:
            return {
                "success": True,
                "message": "默认配置初始化成功"
            }
        else:
            raise HTTPException(status_code=500, detail="默认配置初始化失败")
            
    except BusinessLogicError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"初始化默认配置失败: {str(e)}")


@router.get("/groups", summary="获取配置分组", description="获取所有配置分组信息")
async def get_config_groups(
    category: Optional[ConfigCategory] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取配置分组信息"""
    try:
        service = SystemConfigService(db)
        groups = service.get_all_groups(category)
        
        return {
            "success": True,
            "data": groups,
            "message": "获取配置分组成功"
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取配置分组失败: {str(e)}")


# === 系统状态和监控相关API（待后续阶段实现） ===

@router.get("/status", summary="系统状态", description="获取系统运行状态信息")
async def get_system_status(
    current_user: User = Depends(get_current_user)
):
    """获取系统状态信息（占位符）"""
    return {
        "success": True,
        "data": {
            "status": "running",
            "uptime": "待实现",
            "version": "2.0.0",
            "message": "系统状态监控功能将在后续阶段实现"
        },
        "message": "系统状态获取成功"
    }


@router.get("/health", summary="健康检查", description="系统健康检查接口")
async def health_check():
    """系统健康检查（无需认证）"""
    return {
        "status": "healthy",
        "timestamp": "2025-07-19T12:00:00Z",
        "version": "2.0.0",
        "services": {
            "api": "running",
            "database": "connected",
            "cache": "running"
        }
    }